﻿using MaterialManagement.API.Application.Command.MesWorkOrder;
using MaterialManagement.API.Dtos;
using MaterialManagement.Domain.ERP;
using MaterialManagement.Domain.MesWorkOrder;
using MaterialManagement.ErrorCode;
using MaterialManagement.Infrastructure.Interface;
using MediatR;

namespace MaterialManagement.API.Application.Handler.MesWorkOrder
{
    public class GetCodeMaterialHandler : IRequestHandler<GetCodeMaterialCommand, APIResult<List<BOMMaterialDto>>>
    {
        private readonly IBaseRepository<BOMProductModel> bomProductRepo;
        private readonly IBaseRepository<MaterialInfoModel> materialRepo;

        public GetCodeMaterialHandler(IBaseRepository<BOMProductModel> bomProductRepo,
                                      IBaseRepository<MaterialInfoModel> materialRepo)
        {
            this.bomProductRepo = bomProductRepo;
            this.materialRepo = materialRepo;
        }
        public Task<APIResult<List<BOMMaterialDto>>> Handle(GetCodeMaterialCommand request, CancellationToken cancellationToken)
        {
            APIResult<List<BOMMaterialDto>> result = new APIResult<List<BOMMaterialDto>>();
            var product = bomProductRepo.GetAll().Where(x => x.BOMCode == request.BOMCode).ToList();
            var material = materialRepo.GetAll().ToList();
            var query = from a in product
                    join b in material on a.MaterialCode equals b.MaterialCode
                    select new BOMMaterialDto
                    {
                        BOMCode = a.BOMCode,
                        MaterialCode = a.MaterialCode,
                        Specification = b.Specification,
                        CurrentInventory = b.CurrentInventory,
                        LossRate = a.LossRate,
                        MaterialName = b.MaterialName,
                        Quantity = a.Quantity,
                        Unit = b.Unit
                    };
            result.Message = "显示成功";
            result.Data = query.ToList();
            result.Code = APIEnum.Ok;
            return Task.FromResult(result);
        }
    }
}
